// static/js/schedule_stats.js
;(function(){
  document.addEventListener('DOMContentLoaded', () => {
    const openBtn    = document.getElementById('open-stats-modal');
    const statsModal = new bootstrap.Modal(document.getElementById('statsModal'));
    const startIn    = document.getElementById('stats-start-date');
    const endIn      = document.getElementById('stats-end-date');
    const kwIn       = document.getElementById('stats-keywords');
    const statusIn   = document.getElementById('stats-status');
    const doBtn      = document.getElementById('do-stats');
    const tbody      = document.getElementById('stats-body');
    const panel      = document.getElementById('stats-panel');
    const summary    = document.getElementById('stats-summary');

    openBtn.addEventListener('click', e => {
      e.preventDefault();
      // 重置
      startIn.value = '';
      endIn.value   = '';
      kwIn.value    = '';
      statusIn.value= 'all';
      tbody.innerHTML = '';
      summary.style.display = 'none';
      panel.style.display   = 'block';
      statsModal.show();
    });

    doBtn.addEventListener('click', async () => {
      // 构造参数
      const params = new URLSearchParams();
      if (startIn.value) params.append('start_date', startIn.value);
      if (endIn.value)   params.append('end_date', endIn.value);
      kwIn.value.trim().split(/\s+/).forEach(k=>{
        if (k) params.append('keyword', k);
      });
      if (statusIn.value !== 'all') params.append('status', statusIn.value);

      // 请求
      const res = await fetch('/api/schedules/stats?' + params);
      const list = res.ok ? await res.json() : [];

      // 渲染
      tbody.innerHTML = '';
      let totalCount = 0, totalFee = 0;
      list.forEach(r => {
        totalCount += r.count;
        totalFee   += r.total_fee;
        const tr = document.createElement('tr');
        tr.innerHTML = `
          <td>${r.student}</td>
          <td>${r.count}</td>
          <td>${r.total_fee.toFixed(2)}</td>
        `;
        tbody.appendChild(tr);
      });
      // 合计
      const trTotal = document.createElement('tr');
      trTotal.innerHTML = `
        <td>合计</td>
        <td>${totalCount}</td>
        <td>${totalFee.toFixed(2)}</td>
      `;
      trTotal.style.fontWeight = '600';
      tbody.appendChild(trTotal);

      // 显示条件说明
      const parts = [];
      parts.push(`日期：${startIn.value||'开始'} 至 ${endIn.value||'结束'}`);
      if (kwIn.value.trim()) parts.push(`关键字：${kwIn.value}`);
      parts.push(`状态：${statusIn.value==='all'?'全部':statusIn.value}`);
      summary.textContent = parts.join('；');
      summary.style.display = 'block';

      // 隐藏条件面板
      panel.style.display = 'none';
    });
  });
})();
